package com.webflux.demo.webfluxdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;

/**
 * WebFlux：底层完全基于netty+reactor+springweb完成一个全异步非阻塞的web响应式框架
 * 底层：异步+消息队列（内存）+事件回调机制=整套系统
 * 优点：能使用少量资源处理大量请求
 * <p>
 * https://docs.spring.io/spring-framework/reference/web/webflux.html
 */
public class WebFluxDemoApplication {

    public static void main(String[] args) throws IOException {
        // 快速编写一个能处理请求的服务器
        // 1. 创建一个能处理Http请求的处理器
        HttpHandler handler = (ServerHttpRequest request,
                               ServerHttpResponse response) -> {
            System.out.println(Thread.currentThread() + "request = " + request.getURI());

            // 数据发布者：Mono<DataBuffer>，Flux<DataBuffer>

            // 创建 响应数据的DataBuffer
            DataBufferFactory factory = response.bufferFactory();
            DataBuffer buffer = factory.wrap((request.getURI() + ",hello").getBytes());


            return response.writeWith(Mono.just(buffer));
//            return response.setComplete();
//            return Mono.empty();
        };
        // 2. 启动一个服务器，监听8080端口，接受数据，将数据交给HttpHandler请求处理
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler);
        // 3. 启动Netty服务器
        HttpServer.create()
                .host("localhost")
                .port(8080)
                .handle(adapter)
                .bindNow();

        System.out.println("服务器启动...");
        System.in.read();
        System.out.println("服务器停止...");
    }

}
